package com.xjnt.frameworks.plugin.service;

import java.util.List;

import com.google.common.collect.Lists;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log4jLogger;
import com.jfinal.log.Logger;
import com.jfinal.plugin.IPlugin;
import com.xjnt.frameworks.annotation.Service;
import com.xjnt.frameworks.core.BaseService;
import com.xjnt.frameworks.utils.ClasserKit;

public class ServicePlugin implements IPlugin {
	
	private static final Logger logger = Log4jLogger.getLogger(ServicePlugin.class);

	private boolean isStarted = false;
	
	private boolean autoScan = false;
	/**
	 * 类的默认后缀
	 */
//	private String suffix = "Service";
	
	/**
	 * 需要解析的类包
	 */
	private List<String> includeClassPackages = Lists.newArrayList();

	/**
	 * 是否解析Library库中的所有Jar包
	 */
	private boolean includeAllJarsInLib = false;

	/**
	 * 需要解析的Jar包路径集合
	 */
	private List<String> includeJars = Lists.newArrayList();
	
	public ServicePlugin addScanPackages(String... classPackages) {
		for (String classPkg : classPackages) {
			includeClassPackages.add(classPkg);
		}
		return this;
	}

	public ServicePlugin addScanPackages(List<String> classPackages) {
		if (null != classPackages && !classPackages.isEmpty()) {
			includeClassPackages.addAll(classPackages);
		}
		return this;
	}
	
	public ServicePlugin addIncludeJars(String... jars) {
		for (String jar : jars) {
			includeJars.add(jar);
		}
		return this;
	}
	
	private String getAnnoName(Class<? extends BaseService<?>> clazz) {
//		Preconditions.checkArgument(clazz.getSimpleName().endsWith(suffix), clazz.getName()
//				+ " is not annotated with @Service and not end with " + suffix);
//		String action = "/" + StrKit.firstCharToLowerCase(clazz.getSimpleName());
//		action = action.substring(0, action.indexOf(suffix));
//		return action;
		String service = StrKit.firstCharToLowerCase(clazz.getSimpleName());
		return service;
	}

	@Override
	public boolean start() {
		if(isStarted){
			return true;
		}
		List<Class<? extends BaseService<?>>> serviceClasses = ClasserKit.of(BaseService.class)
				.scanPackages(includeClassPackages).includeAllJarsInLib(includeAllJarsInLib).injars(includeJars)
				.search();
		Service service;
		for (Class<? extends BaseService<?>> clazz : serviceClasses) {
			service = clazz.getAnnotation(Service.class);
			String serviceName = null;
			if(null == service){
				if(!autoScan){
					continue;
				}
				serviceName = getAnnoName(clazz);
				ServiceKit.addService(serviceName, clazz);
			} else {
				serviceName = service.value();
				if(StrKit.notBlank(serviceName)){
					ServiceKit.addService(serviceName, clazz);
				} else {
					serviceName = getAnnoName(clazz);
					ServiceKit.addService(serviceName, clazz);
				}
			}
			logger.debug("ServiceKit.addService(" + serviceName + ", " + clazz.getName() + ")");
		}
		return true;
	}

	@Override
	public boolean stop() {
		ServiceKit.clear();
		isStarted = false;
		return true;
	}

}
